package com.hctforgreen.greenservice.utils;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import android.os.CountDownTimer;
import android.os.Handler;
import android.widget.TextView;

/**
 * 考试倒计时
 * 
 * @author Tallen Zhai
 * 
 */
public class ExamCountDownTimer extends CountDownTimer {

	private TextView mTimeTv;

	/**
	 * 剩余秒数
	 */
	private long millisUntilFinished = 0;
	/**
	 * 总时长
	 */
	private long millisInFuture = 0;

	private Handler mTimeOutHandler;
	public ExamCountDownTimer(long millisInFuture, long countDownInterval,
			TextView timeTv, Handler timeOutHandler) {
		super(millisInFuture, countDownInterval);
		this.millisInFuture = millisInFuture;
		mTimeTv = timeTv;
		mTimeOutHandler = timeOutHandler;
		
		mTimeTv.setText(long2String(millisInFuture));
	}

	public String getUsedTime() {
		long timeOut = millisInFuture - millisUntilFinished;
		
		return long2String(timeOut);
		
	}
	

	@Override
	public void onTick(long timeOut) {
		
		this.millisUntilFinished = timeOut;
		
		mTimeTv.setText(long2String(timeOut));
	}
	
	private String long2String(long timeOut){
		//初始化Formatter的转换格式。
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");  
		formatter.setTimeZone(TimeZone.getTimeZone("UTC")); 
		String sTimeOut = formatter.format(timeOut);  
		
		String[] aTimeOut = sTimeOut.split(":");
		String sHour = aTimeOut[0];
		String sMinutes = aTimeOut[1];
		String sSeconds = aTimeOut[2];
		if(sHour.equals("00")){
			return sMinutes + ":" + sSeconds;
		}else{
			return sTimeOut;
		}
	}
	

	@Override
	public void onFinish() {
		millisUntilFinished = 0;
		mTimeTv.setText("00:00");
		mTimeOutHandler.sendEmptyMessage(0);
	}

}
